<?php
/**
 * @file starscontroller.php $
 * @author LinLin (linlin@haibao.com) $
 * @date 2015-11-25 下午2:30:01 $
 * @brief  $
 */
namespace haibao\cms\data\control\stars;

class StarsController extends \haibao\cms\data\BaseMysql {

	public function __construct(){
		parent::__construct('\haibao\cms\model\data\Base');
	}
	
	/**
	 * 获取明星资讯/图集
	 */
	public function getRecommendStarsArticle($articleArr = array(),$imageCollArr = array()){
		$articleList = $imageCollList = array();
		if($articleArr){
			$articleStr = preg_replace('/\d+/', '%s', implode(',', $articleArr));
			$sql = 'SELECT
						Article.Id,
						Article.PublishId,
						Article.Title,
						ArticleTag.ParentId
					FROM
						Article
					LEFT JOIN ArticleTag ON Article.Id = ArticleTag.ArticleId
					WHERE
						Article.Id IN ('.$articleStr.')
					AND ArticleTag.IsPrimaiy = %s AND Article.Level >= 2';
			array_push($articleArr,\haibao\cms\model\data\ArticleTag::PRIMAIY_IS);
			$articleResult = $this->query($sql, $articleArr);
			while ($row = $articleResult->fetch_assoc()){
				$articleList[$articleResult->getData('Id')] = $row;
			}
		}
		if($imageCollArr){
			$imageCollStr = preg_replace('/\d+/', '%s', implode(',', $imageCollArr));
			$sql = 'SELECT
						ImageCollective.Id,
						ImageCollective.Title,
						ImageCollectiveTag.ParentId,
						ImageCollectiveArticle.ArticleId,
						Article.PublishId
					FROM
						ImageCollective
					LEFT JOIN ImageCollectiveTag ON ImageCollective.Id = ImageCollectiveTag.ImageCollectiveId
					LEFT JOIN ImageCollectiveArticle ON ImageCollective.Id = ImageCollectiveArticle.ImageCollectiveId
					LEFT JOIN Article ON ImageCollectiveArticle.ArticleId = Article.Id
					WHERE
						ImageCollective.Id IN ('.$imageCollStr.')
					AND ImageCollectiveTag.IsPrimaiy = %s AND ImageCollective.Level >= 2';
			array_push($imageCollArr,\haibao\cms\model\data\ArticleTag::PRIMAIY_IS);
			$imageCollResult = $this->query($sql, $imageCollArr);
			while ($row = $imageCollResult->fetch_assoc()){
				$imageCollList[$imageCollResult->getData('Id')] = $row;
			}
		}
		return array($articleList,$imageCollList);
	}

	/**
	 * 明星人气榜
	 * @param string $starType 明星类型
	 * @param string $gender 性别
	 * @return Ambigous <multitype:, multitype:unknown string , \haibao\cms\data\control\stars\$oneStarInfo, NULL>
	 */
	public function getPopularityStar($starType = null,$gender = null){
		$containType = '';
		if($starType && !is_array($starType)){
			$containType = " and StarTypes like '%$starType%'";
		}
		if($starType && is_array($starType)){
			$containType = ' and (';
			foreach($starType as $val){
				$containType .= "  StarTypes like '%$val%' or";
			}
			$containType=substr($containType,0,-2);
			$containType .= ")";
		}
		$containGender = '';
		if($gender){
			$containGender = ' and Gender = '.$gender;
		}
		$sql = "select a.TagId,a.NameCn,a.NameEn from Celebrity as a left join CelebrityRiseCount as b on a.Id = b.CelebrityId where a.TagType = 4 and a.Status = 1 $containType $containGender order by b.WeightCount desc limit 7";
		//echo $sql;
		$starResult = $this->query($sql);
		$popularityStar = $tagIdArr = $starUrlArr = array();
		while($row = $starResult->fetch_assoc()){
			array_push($popularityStar,$row);
		}
		if($popularityStar){
			foreach($popularityStar as $key=>$val){
				$tagIdArr[] = $val['TagId'];
			}
			$starInfoArr = $this->getStarDetailByTagId($tagIdArr);
			$starImageArr = $this->getStarAvator($tagIdArr);
			$firstStarImage = $this->getStarAvator($tagIdArr[0],2);
			foreach($starImageArr as $key=>$val){
				if($firstStarImage['CelebrityId'] == $val['CelebrityId']){
					$starImageArr[$key]['ImageId'] = $firstStarImage['ImageId']; 
				}
			}
			foreach($starImageArr as $key=>$val){
				$starUrlArr[$key] = $val['ImageId'];
			}
			$images = \haibao\cms\business\ImageLibrary::getImageUrlById($starUrlArr);
			foreach($starImageArr as $key=>$val){
				$imageId = $val['ImageId'];
				if(isset($images[$imageId])){
					$starImageArr[$key]['ImageUrl'] = $images[$imageId];
				}
			}
			foreach($popularityStar as $k=>$v){
				$tagId = $v['TagId'];
				if(isset($starImageArr[$tagId])){
					$popularityStar[$k]['ImageUrl'] = $starImageArr[$tagId]['ImageUrl'];
				}
				if(isset($starInfoArr[$tagId])){
					$popularityStar[$k]['StarUrl'] = \haibao\classlibrary\Config::getConfig(\haibao\classlibrary\Config::CLASSLIBRARY_CONFIG_HOST_STARS).$starInfoArr[$tagId]['Url'];
				}
			}
		}
		return $popularityStar;
	}
	
	/**
	 * 明星猜猜猜
	 */
	public function getArticleByTagId($tagId){
		$sql = "select a.Id,a.Title,a.PublishId,c.PicUrl from Article as a left join ArticleTag as b on a.Id = b.ArticleId left join ArticleImage as c on a.Id=c.ArticleId where a.Status = 0 and a.Published = 1 and b.TagId = %s  order by a.PublishTime desc limit 1";
		//$sql = "select a.Id,a.Title,a.PublishId,c.PicUrl from Article as a left join ArticleTag as b on a.Id = b.ArticleId left join ArticleImage as c on a.Id=c.ArticleId where a.Status = 0 and a.Published = 1 and b.TagId = %s and a.Id= 1779718";
		$result = $this->query($sql, array($tagId))->fetch_assoc();
		return $result;
	}
	
	public function getChoiceByArticleId($articleId){
		$sql = 'select b.* from ArticleVote as a left join ArticleVoteProperty as b on a.Id = b.ArticleVoteId where a.ArticleId = %s';
		$result = $this->query($sql, array($articleId));
		$voteStarList = array();
		while($row = $result->fetch_assoc()){
			array_push($voteStarList,$row);
		}
		return $voteStarList;
	}
	
	/**
	 * 明星般配
	 */
	public function getStarMached($change = null,$userId = null){
		if($change && $userId == ''){
			$sqlLove = 'select * from CelebrityRelation where RelationTypeId = 2 order by rand() limit 1';
			$loveResult = $this->query($sqlLove)->fetch_assoc();
		}else if($change && $userId != ''){
			$sqlLove = 'SELECT * from CelebrityRelation where RelationTypeId = 2 and Id not in (select RelationId from CelebrityRelationUser where UserId = %s )  order by rand() limit 1';
			$loveResult = $this->query($sqlLove,array($userId))->fetch_assoc();
		}else{
			$sqlLove = 'select * from CelebrityRelation where RelationTypeId = 2 order by Id desc limit 1';
			$loveResult = $this->query($sqlLove)->fetch_assoc();
		}
		return $loveResult;
	}
	
	public function getStarLoveInfo($loveStar){
		$loveStarTagId = $imgId = $loveMatchArr = array();
		array_push($loveMatchArr,$loveStar['MastarCelebrity']);
		array_push($loveMatchArr,$loveStar['JoinCelebrity']);
		$loveStarResult = $this->getStarDetail($loveMatchArr);
		if(isset($loveStarResult) && $loveStarResult){
			foreach($loveStarResult as $key=>$val){
				$loveStarTagId[]= $val['tag_id'];
			}
			$imgId = $this->getStarInfoImg($loveStarTagId);
			foreach($loveStarResult as $key=>$val){
				if(isset($imgId[$key])){
					$loveStarResult[$key]['ImageUrl'] = $imgId[$key]['ImageUrl'];
				}
			}
		}
		return $loveStarResult;
	}
	
	/**
	 * 获取尚道数据
	 * @return NULL
	 */
	public function getShangDaoInfo(){
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
		$sql = 'select * from shiondo where status = 1 and pubshied = 1 order by dateorder desc limit 1';
		return  $this->query($sql)->fetch_assoc();
	}
	
	/**
	 * 通过明星Id获取明星粉丝数
	 */
	public function getStarFansByTagIdArr($tagIdArr){
		$starFansInfo = array();
		$tagIdStr = preg_replace('/\d+/', '%s', implode(',', $tagIdArr));
		$sql = 'select b.Id,a.FansCount,b.TagId from CelebrityRiseCount as a left join Celebrity as b on a.CelebrityId = b.Id where b.TagId in ('.$tagIdStr.')';
		$starFansResult = $this->query($sql,$tagIdArr);
		while($row = $starFansResult->fetch_assoc()){
			$starFansInfo[$row['TagId']] = $row;
		}
		return $starFansInfo;
	}
	
	/**
	 * 通过topic_id获取明星数据(人气榜)
	 * @param $topicId array
	 * @return 明星数据 topic_id  url  tag_id
	 */
	public function getStarDetail($topicIdArr){
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
		$starInfo = $starTagArr = $tagIdStr = array();
		$str = preg_replace('/\d+/', '%s', implode(',', $topicIdArr));
		$sql = 'select tag_id,tag_name,url from tag where topic_id in ('.$str.')';
		$result = $this->query($sql,$topicIdArr);
		while($row = $result->fetch_assoc()){
			$starInfo[$row['tag_id']] = $row;
			$starTagArr[] = $starInfo[$row['tag_id']]['tag_id'];
		}
		return  $this->getCelebrityByTag($starTagArr,$starInfo);
	}
	
	/**
	 * 通过tagId获取Celebrity表中数据 与tag表中url结合
	 * @return 明星数据 tag_name tag_name_en  url  tag_id
	 */
	public function getCelebrityByTag($starTagArr,$starInfo){
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
		$celebrityArr =  array();
		if(isset($starTagArr) && $starTagArr){
			if(isset($starInfo) && $starInfo){
				$tagIdStr = preg_replace('/\d+/', '%s', implode(',', $starTagArr));
				$sql = 'select TagId,NameCn,NameEn from Celebrity where TagId in ('.$tagIdStr.')';
				$starFansResult = $this->query($sql,$starTagArr);
				while($row = $starFansResult->fetch_assoc()){
					$celebrityArr[$row['TagId']] = $row;
				}
				foreach($starInfo as $key=>$val){
					if(isset($celebrityArr[$key])){
						$starInfo[$key]['tag_name'] = $celebrityArr[$key]['NameCn'];
						$starInfo[$key]['tag_name_en'] = $celebrityArr[$key]['NameEn'];
					}
				}
			}
		}
		return $starInfo;
	}
	
	/**
	 * 通过tagId获取明星数据(人气榜)
	 * @param 标签ID $tagId array
	 * @return  明星数据 topic_id  url  tag_id
	 */
	public function getStarDetailByTagId($tagIdArr){
		return \haibao\cms\business\Tag::getTagsById($tagIdArr);
	}
	
	/**
	 * 通过tagId获取明星头像imageid
	 * @param 标签ID数组  $tagIdArr
	 * @param 图片类型 $imageType (默认1 小头像  2大头像)
	 * @return 明星头像ID数组
	 */
	public function getStarAvator($tagIdArr,$imageType = 1){
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
		if($tagIdArr && is_array($tagIdArr)){
			$starAvator = array();
			$sql = "select CelebrityId,ImageId,TagId from CelebrityImage where TagId in (".implode(',',$tagIdArr).") and ImageType = %s";
			$result = $this->query($sql,array($imageType));
			while($row = $result->fetch_assoc()){
				$starAvator[$row['TagId']] = $row;
			}
			return $starAvator;
		}else {
			$sql = 'select CelebrityId,ImageId from CelebrityImage where TagId = %s and ImageType = %s';
			return $this->query($sql,array($tagIdArr,$imageType))->fetch_assoc();
		}
	}
	
	/**
	 * 根据tagId获取明星头像地址
	 * @param 标签ID数组 $tagIdArr
	 * @param 头像ID,url数组 $imgIdArr
	 * @return 明星头像id+地址(数组)
	 */
	public function getStarInfoImg($tagIdArr){
		$imgIdArr = $this->getStarAvator($tagIdArr);
		if($imgIdArr){
			$newImages = array();
			foreach($imgIdArr as $key=>$val){
				$newImages[$key] = $val['ImageId'];
			}
			$images = \haibao\cms\business\ImageLibrary::getImageUrlById($newImages);
			foreach($imgIdArr as $key=>$val){
				$imageId = $val['ImageId'];
				if(isset($images[$imageId])){
					$imgIdArr[$key]['ImageUrl'] = $images[$imageId];
				}else{
					$imgIdArr[$key]['ImageUrl'] = '';
				}
			}
		}
		return $imgIdArr;
	}
	
	
	
	/**
	 * 获取今日推荐明星
	 * @return 明星基本信息(未关联文章图集头像等)
	 */
	public function getTodayRecommendStars($nowDate = null,$celebrityIdArr = array(), $limit = null){
		$starList = $starTagArr  = array();
		$tempLimit = 3;
		if($celebrityIdArr){
			$str = preg_replace('/\d+/', '%s', implode(',', $celebrityIdArr));
			$sql = 'select a.Id,a.TagId,a.NameEn,a.NameCn,a.Birthday,c.XingZuo,b.EditFansNum as FansCount from Celebrity as a join CelebrityInfo as c on a.Id = c.CelebrityId left join CelebrityRiseCount as b on a.Id = b.CelebrityId where a.Id in ('.$str.') and a.Status = 1 limit 3';
			$result = $this->query($sql,$celebrityIdArr);
			while ($row = $result->fetch_assoc()){
				$starList[$row['TagId']] = $row;
				array_push($starTagArr,(int)$row['TagId']);//手动
			}
		}
		if(count($starList) < $tempLimit){
			if($nowDate){
				$conBirth = '';
				if(count($starTagArr)>0){
					$conBirth = " and a.TagId not in (".implode(',', $starTagArr).")";
				}
				$temp = $tempLimit-count($starList);
				$sql = "select a.Id,a.TagId,a.NameEn,a.NameCn,a.Birthday,c.XingZuo,b.EditFansNum as FansCount from Celebrity as a join CelebrityInfo as c on a.Id = c.CelebrityId left join CelebrityRiseCount as b on a.Id = b.CelebrityId where a.Birthday like '%$nowDate' and a.Status = 1 $conBirth limit $temp";
				$result = $this->query($sql);
				while ($row = $result->fetch_assoc()){
					$starList[$row['TagId']] = $row;
					$starList[$row['TagId']]['IsBirthday'] = 1;
					array_push($starTagArr,(int)$row['TagId']);
				}
			}
			if(count($starList) < $tempLimit){
				$starTagIdArr = array();
				$tempQueryData = $starTagArr;
				$conType = '';
				if(count($starTagArr)>0){
					$str = preg_replace('/\d+/', '%s', implode(',', $starTagArr));
					$conType = ' where `starinfo`.StarTagId not in ('.$str.')';
				}
				$sql = "SELECT StarTagId
				FROM (
				select a.StarTagId,a.PublishTime from `InformationStar` as a left join Celebrity as b
            	   on a.StarTagId = b.TagId 
                   where b.`Status` = 1 ORDER BY a.PublishTime desc
				)
				`starinfo` $conType  GROUP BY StarTagId ORDER BY PublishTime desc limit %s";
				array_push($tempQueryData,$tempLimit-count($starList));
				$result = $this->query($sql,$tempQueryData);
				while ($result->fetch_assoc()){
					array_push($starTagIdArr,$result->getData('StarTagId'));
				}
			
				$str = preg_replace('/\d+/', '%s', implode(',', $starTagIdArr));
				$sql = 'select a.Id,a.TagId,a.NameEn,a.NameCn,a.Birthday,c.XingZuo,b.FansCount from Celebrity as a join CelebrityInfo as c on a.Id = c.CelebrityId left join CelebrityRiseCount as b on a.Id = b.CelebrityId where a.Status = 1 and a.TagId in ('.$str.')';
				$result = $this->query($sql,$starTagIdArr);
				while ($row = $result->fetch_assoc()){
					$starList[$row['TagId']] = $row;
					array_push($starTagArr,(int)$row['TagId']);
				}
			
			}
		}
		return $starList;
	}
	
	/**
	 * 获取明星关联的资讯信息
	 * @param 标签ID数组 $starTagIdArr
	 * @return 明星关联文章图集的Id  数组的键为明星TagId
	 */
	public function getInfoStars($starTagIdArr,$limit = 3){
		$infoStarsArr = array();
		if(is_array($starTagIdArr)){
			$str = preg_replace('/\d+/', '%s', implode(',', $starTagIdArr));
			$sql = 'SELECT
					StarTagId,
					group_concat(`starinfo`.InfoId order by `starinfo`.PublishTime desc) as InfoId,
					group_concat(`starinfo`.InfoType order by `starinfo`.PublishTime desc) as InfoType
				FROM
					(
						SELECT
							*
						FROM
							`InformationStar`
						WHERE
							StarTagId IN ('.$str.')
					) `starinfo`
				GROUP BY
					`starinfo`.StarTagId';
			$result = $this->query($sql,$starTagIdArr);
			while($result->fetch_assoc()){
				$infoIdArr = array_slice(explode(',',$result->getData('InfoId')),0,$limit);
				$infoIdType = array_slice(explode(',',$result->getData('InfoType')),0,$limit);
				$infoStarsArr[$result->getData('StarTagId')] = array_combine($infoIdArr, $infoIdType);
			}
		}
		return $infoStarsArr;
	}
	
	/**
	 * 根据明星首字母获取数据
	 */
	public function getStarListByLetter($firstLetter,$limit=14){
		
		$starList = array();
		if($firstLetter == 'OTHER'){
			$str='';
			for($I=ord('a');$I<=ord('z');$I++){
				$str .= "'".chr($I)."',";
			}
			$str = substr($str,0,-1);
		}
		if($firstLetter == 'OTHER'){
			$sql = "select a.Id,a.TagId,a.NameCn,a.NameEn,b.EditFansNum as FansCount FROM `Celebrity` as a left join `CelebrityRiseCount` as b on a.Id = b.CelebrityId WHERE a.STATUS = %s and a.TagType = 4 and a.Pinyin_en not in ($str) order by b.FansCount desc limit %s";
			$result = $this->query($sql,array(\haibao\cms\model\data\Celebrity::STATUS_ENABLE,$limit));
		}else{
			$sql = "SELECT a.Id,a.TagId,a.NameCn,a.NameEn,b.EditFansNum as FansCount FROM `Celebrity` as a left join `CelebrityRiseCount` as b on a.Id = b.CelebrityId WHERE a.STATUS = %s AND a.TagType = 4 AND a.Pinyin_en = %s ORDER BY b.FansCount DESC LIMIT %s";
			$result = $this->query($sql,array(\haibao\cms\model\data\Celebrity::STATUS_ENABLE,$firstLetter,$limit));
		}
		while($row = $result->fetch_assoc()){
			array_push($starList,$row);
		}
		return $starList;
	}
	
}